package simpleSpring.service;

import simpleSpring.spring.BeanPostProcessor;
import simpleSpring.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author caihe
 * @date 2022/10/25 9:20
 */
@Component
public class CaiheBeanPostProcessor implements BeanPostProcessor {
    
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        if (bean instanceof UserService) {
            System.out.println("userService postProcessBeforeInitialization before.................");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        if (bean instanceof UserService) {
            System.out.println("userService postProcessAfterInitialization after.................");

            Object instance = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    // 代理逻辑
                    System.out.println("切面逻辑"); 
                    
                    return method.invoke(bean, args);
                }
            });
            return instance;
        }
        return bean;
    }
}
